package ttt;
import player.Player;
import java.util.*;
import javax.swing.event.*;
import gui.*;

public class TicTacToe {
	
	public static final int X_MARK = 1;
	public static final int O_MARK = -1;
	public static final int EMPTY_MARK = 0;

	private Player player1;
	private Player player2;
	private Point lastPlay;
	private int[][] board = new int[3][3];
	private BoardEvaluator eval = new BoardEvaluator();
	private BoardUserInterface gui;
	private int player1Mark = X_MARK;
	private int player2Mark = O_MARK;
	
	public TicTacToe(Player p1, Player p2, BoardUserInterface g) {
		player1 = p1;
		player2 = p2;
		gui = g;
		switchPlayer();
	}
	
	private void switchPlayer() {
		Random random = new Random();
		boolean switchPlayers = random.nextBoolean();
		if(switchPlayers) {
			Player p = player1;
			player1 = player2;
			player2 = p;
		}
	}
	
	public int getPlayerMark(Player p) {
		if(player1 == p)
			return player1Mark;
		else if(player2 == p)
			return player2Mark;
		else
			return EMPTY_MARK;
	}
	
	public int[][] getBoard() {
		return board.clone();
	}
	
	public void reset() {
		board = new int[3][3];
		lastPlay = null;
		switchPlayer();
	}
	
	public boolean isOccupied(int row, int col) {
		return eval.isOccupied(board, row, col);
	}
	
	public char intToChar(int i) {
		String marks = "o x";
		return marks.charAt(i + 1);
	}
	
	public void  drawBoard() {
		gui.drawBoard();
	}
	
	public boolean finished() {
		return eval.status(board) != BoardEvaluator.STATUS_UNDEFIND;
	}
	
	public int getState() {
		return eval.status(board);
	}
	
	public Point getLastPlay() {
		return lastPlay;
	}
	
	public void play() {
		if(finished())
			System.out.println("The game has been finished");
		
		while(!finished()) {
			//printBoard();
			Point p1 = player1.placeMark(this);
			board[p1.getRow()][p1.getColumn()] = player1Mark;
			lastPlay = p1;
			gui.stateChanged(new ChangeEvent(this));
			
			if(finished())
				break;
			
			Point p2 = player2.placeMark(this);
			board[p2.getRow()][p2.getColumn()] = player2Mark;
			lastPlay = p2;
			gui.stateChanged(new ChangeEvent(this));
		}
	}
}
